package com.lishe.lishe.lishe.module.main.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.LocalActivityManager;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentTabHost;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.lishe.lishe.R;
import com.lishe.lishe.asynchttp.LSWebHelper;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.base.BaseApplication;
import com.lishe.lishe.lishe.common.CommonUtils;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.common.LogDog;
import com.lishe.lishe.lishe.module.auth.http.AuthHttpHelper;
import com.lishe.lishe.lishe.module.excitation.fragment.ExcitationFragment;
import com.lishe.lishe.lishe.module.giftnote.fragment.GiftNoteFragment;
import com.lishe.lishe.lishe.module.main.bean.ApkMessage;
import com.lishe.lishe.lishe.module.main.bean.NoticeObject;
import com.lishe.lishe.lishe.module.main.dialog.ShowUpdateDialog;
import com.lishe.lishe.lishe.module.main.http.HttpAppUpdata;
import com.lishe.lishe.lishe.module.mall.fragment.MallFragemtn;
import com.lishe.lishe.lishe.module.me.fragments.MineFragment;
import com.lishe.lishe.lishe.module.shopingcart.activity.ShoppingCartActivity;
import com.lishe.lishe.lishe.utils.AppUtils;
import com.lishe.lishe.lishe.utils.NetWorkUtils;
import com.lishe.lishe.lishe.utils.PermissionUtils;
import com.lishe.lishe.lishe.utils.SharedPreferencesUtils;
import com.lishe.lishe.lishe.utils.Utils;
import com.lishe.lishe.lishe.widget.ConfirmDialog;
import com.lishe.lishe.retrofit.DataResponseListener;

import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

/**
 * Created by lwa on 2017/8/9.
 * 首页
 */
public class MainActivity0 extends BaseActivity {
    String TAG = MainActivity0.class.getSimpleName();
    private FragmentTabHost tabHost;
    private LinkedList<ImageView> lisTabIcons = new LinkedList<>();
    private LinkedList<TextView> lisTabTexts = new LinkedList<>();
    private int[] normolIcns = {R.mipmap.store_icon, R.mipmap.company_normal_icon, R.mipmap.me_icon};
    private int tabPage = 0;
    LocalActivityManager mLocalActivityManager;
    ShoppingCartActivity shoppingCartActivity;

    private long downloadId = -1;//下载任务ID
    private DownloadManagerReceiver receiver;//下载广播监听

    /**
     * 从起他页面跳转到MainActivity
     *
     * @param activity
     */
    public static void jump(Activity activity) {
        Intent intent = new Intent(activity, MainActivity0.class);
        activity.startActivity(intent);
    }

    public static void jump(Activity activity, int page) {
        Intent intent = new Intent(activity, MainActivity0.class);
        intent.putExtra("page", page);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main0);
        tabPage = getIntent().getIntExtra("page", 0);
        isChangeStatus(true);
        initView();
        if (BaseApplication.getInstace().showUpdateDialog) {
            BaseApplication.getInstace().showUpdateDialog = false;
            getAPKNewVersion();

            //获取app通告
            getNotice();
        }
    }

    /**
     * 获取通告
     */
    private void getNotice() {
        HttpAppUpdata.getNotice(new DataResponseListener<List<NoticeObject>>() {
            @Override
            public void onSuccess(List<NoticeObject> dataResponse) {
                if (dataResponse != null && dataResponse.size() > 0) {
                    NoticeObject notice = dataResponse.get(0);
                    String[] noticeIds = SharedPreferencesUtils.getNoticeID().split(",");
                    boolean isShow = true;
                    for (int i = 0; i < noticeIds.length; i++) {
                        if (noticeIds[i].equals(notice.getId())) {
                            isShow = false;
                            break;
                        }
                    }
                    if (isShow)
                        showNoticeDialog(notice);
                }
            }

            @Override
            public void onFail(String failMessage) {
//                toast(failMessage);
            }

            @Override
            public void onError(Throwable e) {
//                toast(R.string.network_or_server_exception);
            }
        });
    }

    private void showNoticeDialog(final NoticeObject noticeObject) {
        final Dialog dialog = new Dialog(MainActivity0.this,R.style.MyTransparentDialog);
        View view = View.inflate(MainActivity0.this, R.layout.dialog_show_notice, null);
        TextView content = view.findViewById(R.id.content);
        TextView known = view.findViewById(R.id.known);
        final ImageView dismiss = view.findViewById(R.id.dismiss);

        content.setText(noticeObject.getContent());
        known.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferencesUtils.saveNoticeID(noticeObject.getId());
                dialog.dismiss();
            }
        });

        dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferencesUtils.clearNoticeID();
                dialog.dismiss();
            }
        });
        dialog.setContentView(view);
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = Utils.dip2px(MainActivity0.this,280);
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        dialog.getWindow().setAttributes(lp);
        dialog.show();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initView() {
        tabHost = findViewById(R.id.tab_host);
        tabHost.setup(MainActivity0.this, getSupportFragmentManager(), android.R.id.tabcontent);
        lisTabIcons.clear();
        lisTabTexts.clear();
        //各个模块入口.setContent(new Intent(this, GiftNoteActivity.class)));
//
//        tabHost.addTab(tabHost.newTabSpec("giftRecord").setIndicator(initIndicator(R.mipmap.giftnote_icon, getString(R.string.gift_recoder))), GiftNoteFragment.class, null);
//        tabHost.addTab(tabHost.newTabSpec("mall").setIndicator(initIndicator(R.mipmap.store_icon, getString(R.string.mall))).setContent(new Intent(this, MallActivity.class)));
        tabHost.addTab(tabHost.newTabSpec("mall").setIndicator(initIndicator(R.mipmap.store_icon, getString(R.string.mall))), MallFragemtn.class, null);
        tabHost.addTab(tabHost.newTabSpec("excitation").setIndicator(initIndicator(R.mipmap.company_normal_icon, getString(R.string.company_main))), ExcitationFragment.class, null);
//  tabHost.addTab(tabHost.newTabSpec("shoppingCart").setIndicator(initIndicator(R.mipmap.shopping_cart_normal, getString(R.string.shopping_cart))), ShoppingCartFragment.class, null);
        tabHost.addTab(tabHost.newTabSpec("mine").setIndicator(initIndicator(R.mipmap.me_icon, getString(R.string.mine))), MineFragment.class, null);


        {//拦截点击tab事件，判断是否登录，add by lanyanbo
//            tabHost.getTabWidget().getChildTabViewAt(0).setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    setCurrentTabOrToAuth(0);
//                }
//            });
            //tabHost.getTabWidget().getChildTabViewAt(1).setOnClickListener(this);
            tabHost.getTabWidget().getChildTabViewAt(1).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    setCurrentTabOrToAuth(1);
                }
            });
            tabHost.getTabWidget().getChildTabViewAt(2).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    setCurrentTabOrToAuth(2);
                }
            });
        }

        tabHost.setCurrentTab(tabPage); // 设置第一次打开时默认显示的标签，
        lisTabIcons.get(tabPage).setImageResource(R.mipmap.store_icon_click);
        lisTabTexts.get(tabPage).setTextColor(Color.parseColor("#ff4138"));
        tabHost.setOnTabChangedListener(tabChangelistenre);
    }

    /**
     * 初始化tab栏
     *
     * @return
     */

    private View initIndicator(int imgId, String tabText) {
        View view = getLayoutInflater().inflate(R.layout.item_main_tab_host_view, null);
        ImageView imgTabIcon = view.findViewById(R.id.tab_icon);
        TextView txtTabText = view.findViewById(R.id.tab_text);
        imgTabIcon.setImageResource(imgId);
        txtTabText.setText(tabText);
        lisTabIcons.add(imgTabIcon);
        lisTabTexts.add(txtTabText);
        return view;
    }

    /**
     * table切换监听
     */
    TabHost.OnTabChangeListener tabChangelistenre = new TabHost.OnTabChangeListener() {
        @Override
        public void onTabChanged(String s) {

            lisTabIcons.get(tabPage).setImageResource(normolIcns[tabPage]);
            lisTabTexts.get(tabPage).setTextColor(getResources().getColor(R.color.gray_6));
            switch (s) {
//                case "giftRecord":
//                    isChangeStatus(false);
//                    tabPage = 0;
//                    lisTabIcons.get(0).setImageResource(R.mipmap.giftnote_icon_click);
//                    lisTabTexts.get(0).setTextColor(Color.parseColor("#ff4138"));
//                    break;
                case "mall":
                    isChangeStatus(true);
                    tabPage = 0;
                    lisTabIcons.get(0).setImageResource(R.mipmap.store_icon_click);
                    lisTabTexts.get(0).setTextColor(Color.parseColor("#ff4138"));
                    break;
                case "excitation":
                    isChangeStatus(true);
                    tabPage = 1;
                    lisTabIcons.get(1).setImageResource(R.mipmap.company_click_icon);
                    lisTabTexts.get(1).setTextColor(Color.parseColor("#ff4138"));
                    break;
                case "mine":
                    isChangeStatus(true);
                    tabPage = 2;
                    lisTabIcons.get(2).setImageResource(R.mipmap.me_icon_click);
                    lisTabTexts.get(2).setTextColor(Color.parseColor("#ff4138"));
                    break;
            }
        }
    };

    /**
     * 自动登录
     *
     * @param tabIndex
     */
    public void setCurrentTabOrToAuth(int tabIndex) {
        if (LSWebHelper.getInstance().isUserLogined()) {
            //如果已经登录，执行默认点击操作
            //由于已经覆写了点击方法，所以需要实现tab切换
            tabHost.setCurrentTab(tabIndex);
            tabHost.getTabWidget().requestFocus(View.FOCUS_FORWARD);

        } else {
            doCheckLoginIfNeedAndRedirectAuth(MainActivity0.this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterDownloadReceiver();
    }

    //以下是：再返回一次退出App功能
    private boolean isExit = false;
    Handler mExitHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {// 处理消息
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            isExit = false;
        }
    };

    // 重写Activity中onKeyDown（）方法  在tab中是不响应的，
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {// 当keyCode等于退出事件值时
            ToQuitTheApp();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
                ToQuitTheApp();
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    // 封装ToQuitTheApp方法
    private void ToQuitTheApp() {
        if (isExit) {
            finish();
        } else {
            isExit = true;
            Toast.makeText(MainActivity0.this, R.string.app_finished, Toast.LENGTH_SHORT).show();
            mExitHandler.sendEmptyMessageDelayed(0, 3000);// 3秒后发送消息
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void changePage(int page) {
        if (tabHost != null) {
            tabHost.setCurrentTab(page);
        }
    }

    /**
     * 沉浸模式
     */
    int option0;
    int color0;

    private void isChangeStatus(boolean isShow) {
        if (isShow) {
            if (Build.VERSION.SDK_INT >= 21) {
                View decorView = getWindow().getDecorView();
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                if (option0 == 0 && color0 == 0) {
                    option0 = decorView.getSystemUiVisibility();
                    color0 = getWindow().getStatusBarColor();
                }

                Log.e("option" + decorView.getSystemUiVisibility(), "color" + getWindow().getStatusBarColor());
                decorView.setSystemUiVisibility(option);
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
        } else {
            if (Build.VERSION.SDK_INT >= 21) {
                View decorView = getWindow().getDecorView();
                decorView.setSystemUiVisibility(option0);
                getWindow().setStatusBarColor(color0);
            }
        }
    }

    private void getAPKNewVersion() {
        HttpAppUpdata.checkApkVersion(1, new DataResponseListener<ApkMessage>() {
            @Override
            public void onSuccess(ApkMessage dataResponse) {
                checkAPKVersion(dataResponse);
            }

            @Override
            public void onFail(String failMessage) {

            }

            @Override
            public void onError(Throwable e) {

            }
        });
    }

    private void registerDownloadReceiver() {
        if (receiver == null) {
            receiver = new DownloadManagerReceiver();
        }
        IntentFilter filter = new IntentFilter();
        //点击通知action
        filter.addAction("android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED");
        //下载完成action
        filter.addAction("android.intent.action.DOWNLOAD_COMPLETE");
        registerReceiver(receiver, filter);
    }

    private void unregisterDownloadReceiver() {
        if (receiver != null) unregisterReceiver(receiver);
    }

    private void checkAPKVersion(ApkMessage dataResponse) {
        //当有新版本更新时，保存新版本的版本名和版本号
        SharedPreferencesUtils.saveAppVersionAndCode(dataResponse.getApp_version(), dataResponse.getApp_code());
        if (dataResponse.getApp_code() > AppUtils.getVersionCode(MainActivity0.this)) {
            if (dataResponse.getApp_update().equals("1") || NetWorkUtils.isWifiConnected(MainActivity0.this)) {
                registerDownloadReceiver();
                showUpdateDialog(dataResponse);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        /**
         * grantResults 返回-1，表示请求权限失败，返回0表示请求权限成功
         */
        boolean success = true;
        for (int i : grantResults) {
            if (i != 0) {
                success = false;
                break;
            }
        }
        if (success) {
            if (requestCode == PermissionUtils.request_WRITE_EXTERNAL_STORAGE && downloadId == -1) {
                downloadId = AppUtils.downLoadApkForDownloadManager(MainActivity0.this, AppUtils.APK_DOWNLOAD_URL);
            }
        } else {
            toast(getString(R.string.get_sdcard_permission_fail_please_to_get_permission_for_setting));
        }
    }

    private void showUpdateDialog(final ApkMessage dataResponse) {
        final ShowUpdateDialog.Builder builder = new ShowUpdateDialog.Builder(this);
        builder.setApkMessage(dataResponse);
        builder.setUpdateListener(new ShowUpdateDialog.UpdateListener() {
            @Override
            public void update() {
                if (dataResponse.getApp_update().equals("1")) {//强制更新
//                    LisheLodingActivity.jump(MainActivity0.this);
                    if (PermissionUtils.isStorageWritePermission(MainActivity0.this) && downloadId == -1) {
                        downloadId = AppUtils.downLoadApkForDownloadManager(MainActivity0.this, AppUtils.APK_DOWNLOAD_URL);
                    }
                } else {
                    if (PermissionUtils.isStorageWritePermission(MainActivity0.this) && downloadId == -1) {
                        downloadId = AppUtils.downLoadApkForDownloadManager(MainActivity0.this, AppUtils.APK_DOWNLOAD_URL);
                        builder.dissmiss();
                    }
                }
            }

            @Override
            public void dismiss() {
                if (dataResponse.getApp_update().equals("1")) {
                    exitApp();
                }
                builder.dissmiss();
            }
        });

        builder.show();
    }

    private void exitApp() {
        BaseApplication.getInstace().showUpdateDialog = true;
        finish();
    }
}
